package com.wsjc.app.map.core;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.wsjc.app.map.App;
import com.wsjc.common.core.constants.CommonConst;
import com.wsjc.common.rabbitmq.impl.RmqProducerUtils;
import com.wsjc.manager.entity.WjDataLog;
import com.wsjc.manager.service.routine.datalog.WjDataLogService;
import com.wsjc.manager.service.rpc.map.WjMapService;

/**
 * <b>功能说明:
 * TODO... 无注释
 * 
 */
@Service("mapPersist")
public class MapPersist {

	private static Logger logger = LoggerFactory.getLogger(MapPersist.class);

    @Autowired
    private WjDataLogService wjDataLogService;

	@Autowired
	private WjMapService wjMapService;
	
	@Autowired
	private RmqProducerUtils rmqProducerUtils;
	
	
    /**
     * 更新地图更新状态.<br/>
     * @param id
     * @param status
     */
    public void updateDataLog(WjDataLog wjDataLog, String mapStatus) {
    	wjDataLog.setMapStatus(mapStatus);
    	wjDataLogService.updateData(wjDataLog);
    }


    /**
     * 从数据库中取一次数据用来当系统启动时初始化
     */
    public void initMapDataLogFromDB() throws InterruptedException{
    	
    	logger.info("===>init get map data log from database");

        // 组装查询条件，通知状态不成功，并且还没有超过最大通知次数的
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("mapStatus", CommonConst.DATA_STATUS_CREATE); // 创建状态

        List<WjDataLog> dataLogList = wjDataLogService.listBy(paramMap);
        if (dataLogList == null || dataLogList.isEmpty()) {
        	logger.info("app-map|initMapDataLogFromDB| the dataLogList is null or empty..");
            return;
        }

        for (WjDataLog wjDataLog : dataLogList) {
				App.tasks.put(new MapTask(wjDataLog)); // 添加到通知队列(第一次通知)
        }
        logger.info("app-map|initMapDataLogFromDB| init is successful, size: {}", dataLogList.size());
    }


    /**
     * 更新地图
     * @param dataId
     * @param dataType
     * @param hospitalId
     */
	public void mapFlush(WjDataLog dataLog) {
		
		long start = System.currentTimeMillis();
		
		WjDataLog wjDataLog = wjDataLogService.getDataById(dataLog.getId());
		if(!wjDataLog.getMapStatus().equals(CommonConst.DATA_STATUS_SUCCESS)){
			logger.info("flush-map|the datalog mapStatus is CREATE....");
			/**
			 * 刷新地图，调用 mapFlush 。 还要判断这个数据是否为最新，最新则更新，
			 * 继续判断，最新的这条跟redis 记录的结果是否一致，一致则不更新。         
			 */
			String hospitalId = dataLog.getHospitalId();
			String areaId = hospitalId.substring(5, 11);
			wjMapService.flushMap(dataLog.getDetectionResult(), hospitalId, dataLog.getDataType(), areaId,
					dataLog.getOssDir(), dataLog.getDetectionTime());
			
			//修改状态
		    updateDataLog(wjDataLog, CommonConst.DATA_STATUS_SUCCESS);
		}
		
		if(!wjDataLog.getPushStatus().equals(CommonConst.DATA_STATUS_SUCCESS)){
			logger.info("flush-map|the datalog pushStatus is CREATE....send rabbitmq direct push queue...");
			//推送到客户端
			String message = JSONObject.toJSONString(wjDataLog);
			rmqProducerUtils.sendPushData(message, wjDataLog.getId());
		}
		
		long end = System.currentTimeMillis();
		
		logger.info("flush-map| flush map run :" + (end - start) + "ms");
		
	}


}
